import { openStdin } from 'process';
import { operation } from 'retry';
import { KeyboardEvent } from './event'
import { TextModel, SelectionModel } from './models'
import { InsertTextOperation, SetSelectionOperation, RemoveTextOperation } from './operations'
import { ViewProvider } from './view/view_provider'
class Editor {
    textModel_;
    selectionModel_;
    view_;
    viewProvider_;
    eventHandler;
    constructor(container) {
        this.container = container 
        this.viewProvider_ = new ViewProvider()
    }
    init () {
        this.textModel_ = new TextModel()
        this.selectionModel_ = new SelectionModel()
        this.view_ = this.viewProvider_.provide('source_and_preview', this.textModel_, this.selectionModel_, this.container)
        this.eventHandler = new KeyboardEvent(this, this.container, this.view_)
        this.eventHandler.addListeners()
    }

    getTextModel () {
        return this.textModel_
    }

    getSelectionModel () {
        return this.selectionModel_
    }

    apply (operation) {
        operation.apply(this);
    }

    insertTextAtCursor (text) {
        const selection = this.selectionModel_.getSelection()
        let startIndex = selection.anchor
        let cursorIndex;
        if (!this.selectionModel_.isCollapsed()) {
            const removeTextOperation = new RemoveTextOperation(selection.anchor, selection.focus)
            this.apply(removeTextOperation)
            if (this.selectionModel_.isBackward()) {
                startIndex = selection.focus;
            }
        }
        cursorIndex = startIndex + text.length
        const insertTextOperation = new InsertTextOperation(text, startIndex);
        this.apply(insertTextOperation)
        this.setSelection(cursorIndex, cursorIndex)
    }

    deleteTextAtCursor () {
        const selection = this.selectionModel_.getSelection()
        let startIndex = selection.anchor
        if (!this.selectionModel_.isCollapsed()) {
            this.apply(new RemoveTextOperation(selection.anchor, selection.focus));
            if (this.selectionModel_.isBackward()) {
                startIndex = selection.focus;
            }
        } else if (selection.anchor > 0) {
            this.apply(new RemoveTextOperation(selection.anchor - 1, selection.focus));
            startIndex--
        }
        this.setSelection(startIndex, startIndex)
    }


    setSelection(anchor, focus) {
        const selectionOperaction = new SetSelectionOperation({anchor, focus})
        this.apply(selectionOperaction)
    }

    // // 撤销
    // undo () {

    // }

    // // 回退
    // redo () {

    // }
}
export default Editor;